/**
 * 武器选择界面
 */
class WeaponSelectUI extends UIBase{
    private btn_back:BaseButton;
    private img_right:eui.Image;
    private img_left:eui.Image;
    // private lb_desc:eui.Label;
    private lb_condition:eui.Label;
    private knife:knife;
    private lb_name:eui.Label;
    private img_price:eui.Image;
    private lb_price:eui.Label;
    private scrollView:BaseScrollView
    private weapon_list:eui.List;
    private _listDataArr:eui.ArrayCollection;

    public curSelectItem:WeaponSmallItem;
    public curSelectItemId:number;
    private btn_use:BaseButton;
    private btn_take:BaseButton;
    // private btn_buy:BaseButton;

    private group_price:eui.Group;
    private system:particle.ParticleSystem;
    private curSelectIndex:number=0;
    private curPageData;
    private curWeaponListUI:WeaponListUI;
    //商品列表
    private shop_list;

    private img_bg:eui.Image;

    constructor()
    {
        super('WeaponView');
    }

    public addParticle()
    {
        let texture = RES.getRes('leaf_png');
        let config = RES.getRes("leaf_json");
        this.system = new particle.GravityParticleSystem(texture, config);
        this.addChildAt(this.system,1);
        this.system.emitterX = 0;
        this.system.emitterY = 0;
        this.system.start();
    }

    public init()
    {
        super.init(true);
        this.initAnimation();
        this.addParticle();
        this.curSelectIndex = 1;
        WeaponPrase.instance().getWeaponInfo(this.initUI, this);
        this.setDate();
    }

    public setDate()
    {
        if(TimeUtil.getIsNight())
        {
            this.img_bg.source = 'bg2_png';
        }
        else
        {
            this.img_bg.source = 'bg_jpg';
        }
    }

    public initUI(shopList)
    {
        if(!shopList){
            MessageUtil.tips('error');
            return;
        }
        this.shop_list = shopList;
        this.weapon_list.itemRenderer = WeaponListUI;
        let data = this.getListByIndex(0);
        EffectUtil.instance().flyObj(this.knife, 300, 10);
        this.UpdateUI(data, 0);
    }

    public addEvent()
    {   
        this.btn_back.addTapHandler(this.close, this);
        this.btn_use.addTapHandler(this.UseHandle, this);
        this.btn_take.addTapHandler(this.takeWeapon, this);
        this.img_left.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lastPage, this);
        this.img_right.addEventListener(egret.TouchEvent.TOUCH_TAP, this.nextPage, this);
        GameUtil.addEventListener(EventConst.CHANGE_PAGE, this.changeUI, this);
        GameUtil.addEventListener(EventConst.EVENT_SCROLL_COMPLETE, this.ScrollerComplete, this);
    }

    protected lastPage()
    {
        this.scrollView.scrollToLast();
    }

    protected nextPage()
    {
        this.scrollView.scrollToNext();
    }

    //待优化 todo
    protected takeWeapon()
    {
        if(this.curPageData)
        {
            let page = this.curPageData.page;
            let condition = this.curPageData.price;
            if(condition == '')
            {
                MessageUtil.tips('达成指定条件获得');
                return;
            }
            let good_list:string = this.curPageData.good_list;
            let good_arr = good_list.split(',');
            let randomList = [];
            for(let v of good_arr)
            {
                if(!RoleCache.instance().judgeIsHaveWeapon(v))
                {
                    randomList.push(good_arr.indexOf(v));
                }
            }
            if(randomList.length <= 0)
            {
                MessageUtil.tips('本页已经全部拥有了啊！')
                return;
            }
            
            if(condition && condition != '')
            {
                let result = ConditionUtil.instance().judgeConditon(condition);
                if(result == 1)
                {
                    MessageUtil.tips('金币不足');
                }
                else if(result == 2)
                {
                    MessageUtil.tips('钻石不足');
                }
                else if(result == 0)
                {
                    //条件达成处理
                    let data = {
                        page:page,
                        randomList:randomList
                    }
                    this.touchChildren = false;
                    WeaponPrase.instance().buyWeapon(data,this.buyWeaponSuccess, this);
                }
            }
        }
        else
        {
            MessageUtil.tips('不知名的错误！！')
        }
    }

    protected buyWeaponSuccess(data)
    {
        if(this.curWeaponListUI)
        {
            this.curWeaponListUI.showRandom(data, this.afterShowAnimation, this);
        }
    }

    protected afterShowAnimation(parma)
    {
        this.touchChildren = true;
        GameUtil.openAwardUI('1_'+parma.itemData.id+'_1');
    }

    public ScrollerComplete(e:BaseEvent)
    {
        let parma = e.param;
        let index = parma['item'];
        if(this.curSelectIndex != 1)
        {
            let comp = this.weapon_list.getElementAt(index) as WeaponListUI;
            if(comp)
            {
                let data = comp.da;
                if(data)
                {
                    this.curPageData = data;
                    this.curWeaponListUI = comp;
                    let price = data['price'];
                    let condiitonData = ConditionUtil.instance().parseConditon(price);
                    if(condiitonData.icon != '' && price != '')
                    {
                        this.img_price.source = condiitonData.icon;
                        this.img_price.visible = true;
                        this.lb_price.visible = true;
                        this.lb_price.text = 'x'+condiitonData.num;
                        this.lb_condition.visible = false;
                    }
                    else
                    {
                        this.img_price.visible = false;
                        this.lb_price.visible = false;
                        this.lb_condition.visible = true;
                        this.lb_condition.text = '达成指定条件获取';
                    }
                }
            }
        }
    }

    protected UseHandle()
    {
        let curUseWeaponId = RoleCache.instance().curWeaponId;
        if(!this.curSelectItemId)return;
        let hadWeapon = RoleCache.instance().curHadWeapon;
        let data = DataJson.item_define[this.curSelectItemId];
        if(data)
        {
            let weapId = data.relatedId;
            if(curUseWeaponId == weapId)
            {
                MessageUtil.tips('使用中');
                return;
            }
            if(hadWeapon.indexOf(weapId+'') == -1)
            {
                MessageUtil.tips('尚未拥有！');
            }
            else
            {
                let data = {
                    weapon_id:weapId
                }
                WeaponPrase.instance().useWeapon(data, this.close, this);
            }
        }
    }

    protected changeUI(e:BaseEvent)
    {        
        let parma = e.param;
        let index = parma.index;
        this.curSelectIndex = index;
        this.curSelectItem = null;
        let data = this.getListByIndex(index -1);
        this.UpdateUI(data, index-1);
    }

    protected getListByIndex(type)
    {
        let Arr = [];
        let arr = [];
        let obj = {
            id:1,
            page:1,
            good_list:"",
            price:"",
            type:weaponType.self
        }
        if(type == 0)
        {
            //自己
            let list = RoleCache.instance().curHadWeapon;
            let index = 1;
            for(let k in list)
            {		
                let v = list[k];
                if(arr.length >= 9)
                {
                    let good_list = arr.join(',');
                    let clone = JSON.parse(JSON.stringify(obj));
                    clone.good_list = good_list;
                    Arr.push(clone);
                    arr = [];
                    obj.id++;
                    obj.page++;
                }
                arr.push(v);
                if(parseInt(k)+1 == list.length)
                {
                    let clone = JSON.parse(JSON.stringify(obj));
                    let good_list = arr.join(',');
                    clone.good_list = good_list;
                    Arr.push(clone);
                    arr = [];
                }
            }
        }
        else
        {
            let list = this.shop_list;
            for(let k in list)
            {	
                let v = list[k];
                if(v.type == type)
                {
                    Arr.push(v);
                }
            }
        }
        return Arr;
    }

    protected UpdateUI(list, type)
    {
        if(!this._listDataArr)
        {
            this._listDataArr = new eui.ArrayCollection();
        }
        if(type == weaponType.self)
        {
            this.group_price.visible = false;
            this.btn_use.visible = true;
            this.btn_take.visible = false;
        }
        else
        {
            this.group_price.visible = true;
            this.btn_use.visible = false;
            this.btn_take.visible = true;
        }

        this._listDataArr.source = list;
        this.weapon_list.dataProvider = this._listDataArr;
        this.scrollView.initUI();
    }

    public setSelcet(item:WeaponSmallItem)
    {
        if(this.curSelectItem && this.curSelectItem != item)
        {
            this.curSelectItem.cancelSelectState();
        }
        this.curSelectItem = item;
        this.curSelectItemId = item.getData().itemData.id;
        let weaponData = item.getData().weaponData;
        let itemData = item.getData().itemData;
        this.knife.setUI(weaponData);
        // this.lb_desc.text = itemData.desc;
        this.lb_name.text = itemData.name;
        if(weaponData.condition != '')
        {
            let desc = ConditionUtil.instance().parseConditon(weaponData.condition).desc;
            this.lb_condition.text = desc;
        }
    }

    public initAnimation()
    {
        this.img_left.alpha = this.img_right.alpha = 0.5;
        this.LREffect(this.img_right, 1);
        this.LREffect(this.img_left, -1);
    }

    public LREffect(obj, dir)
    {
         var onComplete1:Function = function(){
            if(obj != null){
                var onComplete2:Function = function(){
                    egret.Tween.get(obj).to({
                     alpha:0.5,
                     x:obj.x - dir * 20
                },500).call(onComplete1,this);  
                }
                egret.Tween.get(obj).to({
                    alpha:1,
                    x:obj.x + dir * 20
                }, 500).call(onComplete2, this);
            }
        };
        onComplete1();
    }

    protected close()
    {
        this.remove(2);
    }

    public removeEvent()
    {
        this.btn_back.removeTapHandler();
        this.btn_use.removeTapHandler();
        this.btn_take.removeTapHandler();
        this.img_left.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.lastPage, this);
        this.img_right.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.nextPage, this);
        GameUtil.removeEventListener(EventConst.CHANGE_PAGE, this.changeUI, this);
        GameUtil.removeEventListener(BaseScrollView.EVENT_SCROLL_COMPLETE, this.ScrollerComplete);
    }

    public clear()
    {
        super.clear();
        this.curSelectItem = null;
        this.weapon_list.dataProvider = null;
        this.weapon_list.itemRenderer = null;
        this._listDataArr = null;
        this.curSelectItemId = null;
        this.system.stop();
        this.system = null;
    }
}

window['WeaponSelectUI'] = WeaponSelectUI;